#!/bin/sh

while getopts ":p:s:v:" opt; do
  case $opt in
  p)
    port=$OPTARG
    ;;
  v)
    version=$OPTARG
    ;;
  ?) ;;

  esac
done

if [ -z "$version" ]; then
  echo "请指定发布版本：使用 -v 参数"
  exit 0
fi

home=$(
  cd "$(dirname $0)"
  pwd
)
cd "${home}"
source "${home}/restart.conf"

if [ -z "$port" ]; then
  port=$defaultPort
  echo "没有指定端口，使用默认端口:$port"
fi

echo "发布版本为："$version "服务端口为：$port"
jar="$serverName-$version.jar"
> "${home}"/logs/catalina.out
ps -ef | grep java | grep "port=${port}" | grep -v 'grep' | awk '{print $2}' | xargs -i{} kill {}

cd "${home}"
nohup java -jar -XX:MetaspaceSize="$metaspaceSize" -XX:MaxMetaspaceSize="$maxMetaspaceSize" -Xmn"$mn" -Xms"$ms" -Xmx"$mx" -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC -Dserver.port="${port}" "${jar}" >logs/catalina.out 2>&1 &

  for i in {1..20}; do
    result=$(grep "启动成功" ${home}/logs/catalina.out)
    if [[ "$result" != "" ]]; then
      echo "${serverName} 启动成功......."
      exit 0
    else
      echo "${serverName} 正在启动中......."
      sleep 5s
    fi
  done
